using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Infaction;
using RBAC.Api.Writh.Command.Users;
using System.Diagnostics;

namespace RBAC.Api.Writh.CommandHandler.Users
{
    /// <summary>
    /// 修改用户状态处理程序
    /// </summary>
    public class UpdateUserStateCommandHandler : IRequestHandler<UpdateUserStateCommand, APIResult<object>>
    {
        private readonly IBaseRepositry<User> dal;
        private readonly ILogger<UpdateUserStateCommandHandler> logger;

        public UpdateUserStateCommandHandler(IBaseRepositry<User> baseRepositry, ILogger<UpdateUserStateCommandHandler> logger)
        {
            dal = baseRepositry;
            this.logger = logger;
        }

        public async Task<APIResult<object>> Handle(UpdateUserStateCommand request, CancellationToken cancellationToken)
        {
            var stopwatch = Stopwatch.StartNew();
            APIResult<object> result = new APIResult<object>();
            
            try
            {
                logger.LogInformation("开始处理修改用户状态请求，用户ID: {Id}", request.Id);
                
                // 获取用户实体
                var user = dal.GetAll().FirstOrDefault(u => u.Id == request.Id);
                if (user == null)
                {
                    result.Code = ResultCode.Fail;
                    result.Message = $"未找到ID为{request.Id}的用户";
                    logger.LogWarning("修改用户状态失败：未找到对应用户, ID: {Id}", request.Id);
                    return result;
                }

                // 修改状态
                user.State = request.State;
                user.ModifyTime = DateTime.Now;
                
                await dal.Update(user);
                
                result.Code = ResultCode.Success;
                result.Message = $"修改用户状态成功，当前状态: {(request.State ? "启用" : "禁用")}";
                logger.LogInformation("修改用户状态成功, ID: {Id}, 新状态: {State}", request.Id, request.State);
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"修改用户状态失败: {ex.Message}";
                logger.LogError(ex, "修改用户状态出现异常, ID: {Id}, 错误: {Message}", request.Id, ex.Message);
            }
            finally
            {
                stopwatch.Stop();
                logger.LogInformation("处理修改用户状态请求完成, 耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }

            return result;
        }
    }
} 